package com.movitech.mobile.cz.base.sys.bizcontroller;

import com.movitech.mobile.cz.base.common.util.Doc2Pdf;
import com.movitech.mobile.cz.base.sys.entity.SAttachment;
import com.movitech.mobile.cz.base.sys.service.SAttachmentService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2018/3/12.
 */
@RestController
@RequestMapping("/v1/public/authdownload")
@Api(value = "公共文件下载接口（带token）", description = "公共文件下载接口（带token）")
public class DownloadAuthController {
    private static InputStream license;
    private static InputStream cells;

    @Value("${auth.download.file.url}")
    private String authDownloadFileUrl;// = "http://118.144.133.94:9012/filemanage/fileServer/downloadFile?id=";

    @Autowired
    private SAttachmentService sAttachmentService;

    /***
     * 通过路径id，获取下载文件
     * @param request
     * @param response
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public HttpServletResponse download(HttpServletRequest request, HttpServletResponse response) {
        String attachmentPath = request.getParameter("attachmentPath");
        String token = request.getParameter("token");
        String path = authDownloadFileUrl + attachmentPath + "&token="+token;

        SAttachment sAttachment = sAttachmentService.getByAttachmentPath(attachmentPath);
        String fileName = sAttachment.getAttachName();

        String userAgent = request.getHeader("User-Agent");
        //针对IE或者以IE为内核的浏览器：
        if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
            try {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            //非IE浏览器的处理：
            try {
                fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        InputStream inStream = null;
        URLConnection conn = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            response.setCharacterEncoding("UTF-8");
            request.setCharacterEncoding("UTF-8");

            URL url = new URL(path);// http://pic1.5442.com/2013/0607/04/11.jpg
            conn = url.openConnection();
            inStream = conn.getInputStream();
            bis = new BufferedInputStream(inStream);

            // 清空response
            response.reset();
            bos = new BufferedOutputStream(response.getOutputStream());
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);// + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            //response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
//            response.setContentType("application/x-msdownload;");

            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(inStream != null){
                    inStream.close();
                }
                if (bis != null){
                    bis.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return response;
    }

    /**
     * 通过路径id、附件名称，获取下载文件
     * @param request
     * @param response
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/download_direct", method = RequestMethod.GET)
    public HttpServletResponse downloadDirect(HttpServletRequest request, HttpServletResponse response) {
        InputStream inStream = null;
        URLConnection conn = null;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            String attachmentPath = request.getParameter("attachmentPath");
            String token = request.getParameter("token");
            attachmentPath = URLDecoder.decode(attachmentPath, "UTF-8");
            //        String attachmentPath = uploadResultVO.getAttachPath();
            String path = authDownloadFileUrl + attachmentPath + "&token="+token;
            String fileName = request.getParameter("attachmentName");
            //        String fileName =uploadResultVO.getAttachName();
            fileName = URLDecoder.decode(fileName, "UTF-8");
            fileName=fileName.replaceAll(",","");
            response.setCharacterEncoding("UTF-8");
            request.setCharacterEncoding("UTF-8");

            String userAgent = request.getHeader("User-Agent");
            //针对IE或者以IE为内核的浏览器：
            if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
                try {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                //非IE浏览器的处理：
                try {
                    fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            URL url = new URL(path);// http://pic1.5442.com/2013/0607/04/11.jpg
            conn = url.openConnection();
            inStream = conn.getInputStream();
            bis = new BufferedInputStream(inStream);

            // 清空response
            response.reset();
            bos = new BufferedOutputStream(response.getOutputStream());
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);// + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            //response.addHeader("Content-Length", "" + file.length());
            response.setContentType("application/octet-stream");
//            response.setContentType("application/x-msdownload;");

            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(inStream != null){
                    inStream.close();
                }
                if (bis != null){
                    bis.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }


    /**
     * 在线 转换 预览
     * @param request
     * @param response
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/previewPdf", method = RequestMethod.GET)
    public HttpServletResponse previewPdf(HttpServletRequest request, HttpServletResponse response) {
        InputStream inStream = null;
        URLConnection conn = null;
        OutputStream bos = null;
        try {
            String attachmentPath = request.getParameter("attachmentPath");
            String token = request.getParameter("token");
            attachmentPath = URLDecoder.decode(attachmentPath, "UTF-8");
//            if(attachmentPath.endsWith(".doc")||attachmentPath.endsWith(".docx")
//                    ||attachmentPath.endsWith(".docx")||attachmentPath.endsWith(".xls")||
//                    attachmentPath.endsWith(".xlsx")){
//            }else{
//                throw new RuntimeException("文件格式不支持");
//            }
            //        String attachmentPath = uploadResultVO.getAttachPath();
            String path = authDownloadFileUrl + attachmentPath + "&token="+token;
            String fileName = request.getParameter("attachmentName");
            //        String fileName =uploadResultVO.getAttachName();
            fileName = URLDecoder.decode(fileName, "UTF-8");
            fileName=fileName.replaceAll(",","");
            response.setCharacterEncoding("UTF-8");
            request.setCharacterEncoding("UTF-8");

            String userAgent = request.getHeader("User-Agent");
            //针对IE或者以IE为内核的浏览器：
            if (userAgent.contains("MSIE")||userAgent.contains("Trident")) {
                try {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                //非IE浏览器的处理：
                try {
                    fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }

            URL url = new URL(path);
            conn = url.openConnection();
            inStream = conn.getInputStream();

            // 清空response
            response.reset();
            bos = response.getOutputStream();
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);// + new String(fileName.getBytes("UTF-8"), "ISO8859-1"));
            response.setContentType("application/octet-stream");

            if(fileName.endsWith(".xls")||fileName.endsWith(".xlsx")){
                Doc2Pdf.excel2pdf(inStream,bos);
            }else{
                Doc2Pdf.doc2pdf(inStream,bos);
            }
        } catch (Exception e) {
            try {
                response.getWriter().write(e.getMessage());
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        } finally {
            try {
                if(inStream != null){
                    inStream.close();
                }
                if (bos != null){
                    bos.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return null;
    }

}
